/**
 * Created by evantang on 2018/5/25.
 */
import {Component, ElementRef, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {BaseAuthenticateComponent} from "../../shared/component/baseAuthenticate.component";
import {UserService} from "../../service/userService";
import {RestWechat} from "../../entity/RestWechat";
import {User} from "../../entity/User";
import {SMSService} from "../../service/smsService";
import {Observable, Subscription} from "rxjs";
import {DialogService} from "../../service/dialogService";
import {WeUIDialog} from "angular4-weui";
declare var wx: any;
@Component({
  selector: 'app-qrcode-scan',
  templateUrl: 'qrcode-scan.component.html',
  styleUrls: ['./qrcode-scan.component.css']
})
export class QrCodeScanComponent extends BaseAuthenticateComponent {

  smsCode: string;
  phone: string;
  private clock: Subscription;
  count = 60;
  countDown: number;

  @ViewChild('sendMsg') sendMsg: WeUIDialog;

  constructor(protected a_router: Router, public element: ElementRef, public route: ActivatedRoute,
              private _userService: UserService, private smsService: SMSService, public _dialogService: DialogService) {
    super(a_router, element, route, false, _dialogService);
  }

  scan() {
    // let restWechat = new RestWechat();
    // restWechat.openId = this.openid;
    // restWechat.userId = '002@001';
    // this._userService.registerWeChatUser(restWechat).subscribe(
    //   (resp) => {
    //     this._userService.wechatLogin(this.openid).subscribe(
    //       (resp) => {
    //         // 已经存在绑定关系 => 进入系统
    //         if (resp) {
    //           console.log('login' + JSON.stringify(resp))
    //           localStorage.setItem('token', resp.token);
    //           let user = new User();
    //           user.userid = resp.userId
    //           localStorage.setItem('loginUser', JSON.stringify(user));
    //           window.location.href = 'dashboard/task/list';
    //         }
    //       },
    //       err => {
    //         this.handleError(err)
    //       }
    //     )
    //   }
    // )

    wx.scanQRCode({
      needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
      scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
      success: (res) => {
        let restWechat = new RestWechat();
        restWechat.openId = this.openid;
        restWechat.userId = res.resultStr;
        this._userService.registerWeChatUser(restWechat).subscribe(
          (resp) => {
            this._userService.wechatLogin(this.openid).subscribe(
              (resp) => {
                console.log(resp);
                // 已经存在绑定关系 => 进入系统
                if (resp) {
                  localStorage.setItem('token', resp.token);
                  let user = new User();
                  user.userid = resp.userId
                  console.log('user info' + JSON.stringify(user))
                  localStorage.setItem('loginUser', JSON.stringify(user));
                  window.location.href = 'dashboard/task/list';
                }
              },
              err => {
                this.handleError(err)
              }
            )
          }
        )
      }
    });
  }

  getSMSCode() {

    this.count = 60;
    this.smsService.getSMSCode(this.phone).subscribe(
      (resp) => {
        console.log('getSMSCode ' + JSON.stringify(resp))
      }
    )

    this.clock = Observable.interval(1000).map(tick => --this.count).subscribe(timecount => this.countDown = timecount);
  }

  isValid() {
    return (this.count > 0 && this.count < 60) || (!this.phone) || (this.phone.length!==11);
  }

  countingDown() {
    return (this.count > 0 && this.count < 60);
  }

  bindWechatUser() {
    let restWechat = new RestWechat();
    restWechat.openId = this.openid;
    restWechat.phone = this.phone;
    this.smsService.verifySMSCode(this.phone, this.smsCode).subscribe(
      (resp) => {
        if (resp && resp.value) {
          // 短信验证成功之后进行微信用户和系统用户的绑定
          this._userService.registerWeChatUserByPhone(restWechat).subscribe(
            (resp) => {
              this._userService.wechatLogin(this.openid).subscribe(
                (resp) => {
                  console.log(resp);
                  // 已经存在绑定关系 => 进入系统
                  if (resp) {
                    localStorage.setItem('token', resp.token);
                    let user = new User();
                    user.userid = resp.userId
                    localStorage.setItem('loginUser', JSON.stringify(user));
                    window.location.href = 'dashboard/task/list';
                  }
                },
                err => {
                  this.handleError(err)
                }
              )
            }
          )
        } else {
          let dialogOption = {showNOButton: false, content: resp.info, btnOKText: "知道了"};
          for (const key in dialogOption) {
            this.sendMsg[key] = dialogOption[key];
          }
          this.sendMsg.show();
        }

      }
    )
  }

  ngOnDestroy(): void {
    this.clock.unsubscribe();
  }


}
